package db

import (
	"blog_api/conf"
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
	"reflect"
)

var client *elastic.Client

type ArticleDoc struct {
	Id  string `json:"id"`
	Doc string `json:"doc"`
}

/**
 * init
 * @Description: 初始化连接es
 * @Author: Jazk-Z
 */
func init() {
	errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
	var err error
	client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(conf.ES_HOST))
	if err != nil {
		panic(err)
	}
	info, code, err := client.Ping(conf.ES_HOST).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

	esversion, err := client.ElasticsearchVersion(conf.ES_HOST)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch version %s\n", esversion)
}

/**
 * create
 * @Description: 创建
 * @Author: Jazk-Z
 */
func CreateIndex(id string, doc string, index string) (string, error) {
	// 使用结构体
	art := ArticleDoc{
		id,
		doc,
	}
	put, err := client.Index().Index(index).Id(id).BodyJson(art).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Indexed tweet %s to index s%s, type %s\n", put.Id, put.Index, put.Type)
	return put.Result, err
}

/**
 * delete
 * @Description: 删除
 * @Author: Jazk-Z
 */
func DeleteIndex() {
	res, err := client.Delete().Index("megacorp").Id("1").Do(context.Background())
	if err != nil {
		println(err.Error())
		return
	}
	fmt.Printf("delete result %s\n", res.Result)
}

/**
 * update
 * @Description: 修改
 * @Author: Jazk-Z
 */
func UpdateIndex() {
	res, err := client.Update().
		Index("megacorp").
		Id("2").
		Doc(map[string]interface{}{"age": 88}).
		Do(context.Background())
	if err != nil {
		println(err.Error())
	}
	fmt.Printf("update age %s\n", res.Result)
}

/**
 * gets
 * @Description: 查找
 * @Author: Jazk-Z
 */
func FindIndex(id string, index string) bool {
	// 通过id查找
	res, err := client.Get().Index(index).Id(id).Do(context.Background())
	if err != nil {
		panic(err)
	}
	if res.Found {
		fmt.Printf("Got document %s in version %d from index %s, type %s\n",
			res.Id, res.Version, res.Index, res.Type)
		return res.Found
	}
	return false
}

/**
 * query
 * @Description: 搜索
 * @Author: Jazk-Z
 */
func SearchKeyword(keyword string, index string) ([]interface{}, error) {
	var res *elastic.SearchResult
	var err error
	// 取所有
	// res, err = client.Search(index).Do(context.Background())
	// PrintArtDoc(res, err)

	// // 字段相等
	// q := elastic.NewQueryStringQuery("last_name:Smith")
	// res, err = client.Search("megacorp").Query(q).Do(context.Background())
	// if err != nil {
	// 	println(err.Error())
	// }
	// PrintArtDoc(res, err)
	//
	// // 条件查询
	// // 年龄大于30岁的
	// boolQ := elastic.NewBoolQuery()
	// boolQ.Must(elastic.NewMatchQuery("last_name", "smith"))
	// boolQ.Filter(elastic.NewRangeQuery("age").Gt(30))
	// res, err = client.Search("megacorp").Query(q).Do(context.Background())
	// PrintArtDoc(res, err)

	// 短语搜索 搜索about字段中有 rock climbing
	matchPhraseQuery := elastic.NewMatchPhraseQuery("doc", keyword)
	res, err = client.Search(index).Query(matchPhraseQuery).Do(context.Background())
	list := PrintArtDoc(res, err)
	return list, err

	// // 分析 interests
	// aggs := elastic.NewTermsAggregation().Field("interests")
	// res, err = client.Search("megacorp").Aggregation("all_interests", aggs).Do(context.Background())
	// PrintArtDoc(res, err)
}

/**
 * list
 * @Description: 简单分页
 * @Author: Jazk-Z
 * @param size
 * @param page
 */
func List(size, page int) {
	if size < 0 || page < 1 {
		fmt.Printf("param error")
		return
	}
	res, err := client.Search("megacorp").Size(size).From((page - 1) * size).Do(context.Background())
	PrintArtDoc(res, err)
}

/**
 * PrintArtDoc
 * @Description: 打印查询到的ArtDoc
 * @Author: Jazk-Z
 * @param res
 * @param err
 */
func PrintArtDoc(res *elastic.SearchResult, err error) []interface{} {
	var search_res []interface{}

	if err != nil {
		print(err.Error())
		return search_res
	}
	var doc ArticleDoc
	for _, item := range res.Each(reflect.TypeOf(doc)) { // 从搜索结果中取数据的方法
		t := item.(ArticleDoc)
		search_res = append(search_res, t.Id)
	}
	return search_res
}
